package day02;

import java.util.Arrays;
import java.util.HashMap;

/**
 * <a href="https://leetcode-cn.com/problems/two-sum/">1. 两数之和</a>
 */
public class Answer {

    public static void main(String[] args) {
        int[] nums = {3, 3};
        int target = 6;
        int[] ints = twoSum(nums, target);
        System.out.println(Arrays.toString(ints));

        int[] ints1 = twoSum1(nums, target);
        System.out.println(Arrays.toString(ints1));
    }

    /**
     * O(n^2)
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    /**
     * O(n)
     */
    public static int[] twoSum1(int[] nums, int target) {
        int[] index = new int[2];
        // 建立k-v ，一一对应的哈希表
        HashMap<Integer, Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hash.containsKey(nums[i])) {
                index[0] = hash.get(nums[i]);
                index[1] = i;
                return index;
            }
            // 将数据存入 key为补数 ，value为下标
            hash.put(target - nums[i], i);
        }
        return index;
    }

    /**
     * 左神
     */
    public static int[] twoSum2 (int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[] { map.get(target - nums[i]), i };
            }
            map.put(nums[i], i);
        }
        return new int[] { -1, -1 };
    }
}
